package matt.design;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class ViewTasksActivity extends MapActivity {

	public static TasksDataSource datasource;
	private List<Item> values;
	private MapController mapController;
	private MapView mapView;
	private LocationManager locationManager;
	private MyLocationOverlay myLocationOverlay;
	private GeoPoint point, currLoc;
	private ArrayList<Item> closeTasks, taskLocs;
	private Boolean justStarted = false;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.viewtasks_maps); // bind the layout to the activity

		
		
		// Configure the Map
		mapView = (MapView) findViewById(R.id.task_view);
		mapView.setBuiltInZoomControls(true);
		mapView.setHapticFeedbackEnabled(true);
		mapController = mapView.getController();
		mapController.setZoom(18); // Zoom 1 is world view
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());

		//Get all tasks
		datasource = new TasksDataSource(this);
		datasource.open();
		
		values = null;
		try {
			values = datasource.getAllItems(HomepageActivity.CURRENT_USER);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		datasource.close();
		
		//Get's the last known location
		String provider = locationManager.getProviders(true).get(0);
		Location currLocation = locationManager.getLastKnownLocation(provider);
		System.out.println("Current Location: " + currLocation.getLatitude() + " " + currLocation.getLongitude());
				
		closeTasks = new ArrayList<Item>();
		taskLocs = new ArrayList<Item>();
		//puts all tasks with a loction into an array
		for(int i = 0; i < values.size(); i++){
			Boolean ad = values.get(i).getAddress() != null && !values.get(i).getAddress().equals("");
			Boolean lt = values.get(i).getLatitude() != null && !values.get(i).getLatitude().equals("");
			Boolean lg = values.get(i).getLongitude() != null && !values.get(i).getLongitude().equals("");
			if(ad && lt && lg){
				taskLocs.add(values.get(i));
			}
		}
		print(taskLocs);
		//searches for tasks that are within 5 miles
		for(int i = 0; i < taskLocs.size(); i++){
			Location loc = new Location("");
			loc.setLatitude(Integer.parseInt(taskLocs.get(i).getLatitude()));
			loc.setLongitude(Integer.parseInt(taskLocs.get(i).getLongitude()));
			System.out.println("Distance: " + currLocation.distanceTo(loc));
			if(currLocation.distanceTo(loc) < 8046.72E7){ //measured in meters
				closeTasks.add(taskLocs.get(i));
				System.out.println("Close Enough!");
			}
		}
		print(closeTasks);
		
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);
        listOfOverlays.add(myLocationOverlay);
        
        mapView.invalidate();

		myLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapView.getController().animateTo(myLocationOverlay.getMyLocation());
			}
		});
			
		
//		if(point != null){
//	        geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
//	              try {
//	                  List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6()  / 1E6, point.getLongitudeE6() / 1E6, 1);
//	                  currLocation.setText(addresses.get(0).toString());
//	              }
//	              catch (IOException e) {                
//	                  e.printStackTrace();
//	              }
//		}
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public class GeoUpdateHandler implements LocationListener {

		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			point = new GeoPoint(lat, lng);
			if(justStarted){
				mapController.animateTo(point);
				justStarted = true;
			}
			//mapController.setCenter(point);

		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}



	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.enableCompass();
	}

	@Override
	protected void onPause() {
		super.onResume();
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
	}
	
	class MapOverlay extends com.google.android.maps.Overlay
    {		
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) 
        {
            super.draw(canvas, mapView, shadow);                   
            if(closeTasks .size() > 0){
            	for(int i = 0; i < closeTasks.size(); i++){ 
            		//---translate the GeoPoint to screen pixels---
		            Point screenPts = new Point(); 
		            GeoPoint cPoint = new GeoPoint(Integer.parseInt(closeTasks.get(i).getLatitude()), Integer.parseInt(closeTasks.get(i).getLongitude()));
		            mapView.getProjection().toPixels(cPoint, screenPts);
		 
		            //---add the marker---
		            Bitmap bmp = BitmapFactory.decodeResource( getResources(), R.drawable.red_pushpin);            
		            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null); 
		        }
            }
            return true;
        }
        
        //have to declare outside of method...
//        Boolean lPressed = false;
//        long delay = 300;
//        @Override
//        public boolean onTouchEvent(MotionEvent event, MapView mapView) 
//        {
//        	handleLongpress(event);
//        	if(event.getAction() == 1 && lPressed){//user's finger has left the screen and there was a long press
//        		pin = mapView.getProjection().fromPixels( (int) event.getX(), (int) event.getY());
//        		lPressed = false;
//        		
//        		geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
//                try {
//                    List<Address> addresses = geoCoder.getFromLocation(pin.getLatitudeE6()  / 1E6, pin.getLongitudeE6() / 1E6, 1);
//                    String add = "";
//                    if (addresses.size() > 0) 
//                    {
//                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
//                           add += addresses.get(0).getAddressLine(i) + " ";
//                    }
//                    currLocation.setText(add);
//                    
//                }
//                catch (IOException e) {                
//                    e.printStackTrace();
//                }  
//        	}
//			return false;   
//        }
//    
//        private void handleLongpress(final MotionEvent event) {
//          	 
//            if (event.getAction() == MotionEvent.ACTION_DOWN) {
//                // Finger has touched screen.
//                longPressTimer = new Timer();
//                longPressTimer.schedule(new TimerTask() {
//                    @Override
//                    public void run() {
//                    	lPressed = true;
//                    	mapView.performHapticFeedback(1);
//                    }
//     
//                }, delay);
//            }
//     
//            if (event.getAction() == MotionEvent.ACTION_MOVE) {
//                    longPressTimer.cancel();
//            }
//     
//            if (event.getAction() == MotionEvent.ACTION_UP) {
//                // User has removed finger from map.
//                longPressTimer.cancel();
//            }
//     
//                if (event.getPointerCount() > 1) {
//                            // This is a multitouch event, probably zooming.
//                    longPressTimer.cancel();
//                }
//        }
    } 
	
	private void print(ArrayList<Item> array){
		for(int i = 0; i< array.size(); i++){
			if(i == array.size()-1){
				System.out.print(" " + array.get(i) + "\n");
			}
			else if(i == 0)
				System.out.print("\n" + "Elements " + array.get(i));
			else
				System.out.print(" " + array.get(i));
		}
	}
	
}